package com.zhang.controller;

import com.zhang.aspect.HttpAspect;
import com.zhang.domain.Girl;
import com.zhang.domain.Result;
import com.zhang.reposlitory.GirlRepository;
import com.zhang.service.GirlService;
import com.zhang.utils.ResultUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
public class GirlController {

    // 记录日志
    private final static Logger logger = LoggerFactory.getLogger(GirlController.class);

    @Autowired
    private GirlRepository girlRepository;

    @Autowired
    private GirlService girlService;
    /* 查询所有女生列表 */
    @GetMapping(value = "/girls")
    public List<Girl> girlList() {
        // 获取女生列表 查找全部
        return girlRepository.findAll();
    }
    /* 添加一个女生 */
    @PostMapping(value = "/girls")
    public Result<Girl> airlAdd(@Valid Girl girl, BindingResult bindingResult) {
        Result result = new Result();
        if (bindingResult.hasErrors()) {
            //  return null;
            return ResultUtil.error(0, bindingResult.getFieldError().getDefaultMessage());
        }
        girl.setCupSize(girl.getCupSize());
        girl.setAge(girl.getAge());
        return ResultUtil.success(girlRepository.save(girl));
    }

    /* 通过id查询一个女生 */
    @GetMapping(value = "/girls/{id}")
    public Girl girlFindOne(@PathVariable("id") Integer id) {
        return girlRepository.findOne(id);
    }

    /* 更新女生信息 */
    @PutMapping(value = "/girls/{id}")
    public Girl girlUpdate(@PathVariable("id") Integer id, @RequestParam("cupSize") String cupSize, @RequestParam("age") Integer age) {
        Girl girl = new Girl();
        girl.setId(id);
        girl.setCupSize(cupSize);
        girl.setAge(age);
        return girlRepository.save(girl);
    }

    /* 删除一个女生 */
    @DeleteMapping(value = "/girls/{id}")
    public void girlDelete(@PathVariable("id") Integer id) {
        girlRepository.delete(id);
    }

    /* 按照年龄查询女生列表 */
    @GetMapping(value = "girls/age/{age}")
    public  List<Girl> girlListByAge(@PathVariable("age") Integer age) {
        return girlRepository.findByAge(age);
    }

    /* 事务管理，添加两个女生 */
    @PostMapping(value = "girls/two")
    public void girlTwo() {
        girlService.inserTwo();
    }

    @GetMapping(value = "girls/getAge/{id}")
    public void getAge(@PathVariable("id") Integer id) throws Exception{
        girlService.getAge(id);
    }
}
